<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { exportData, importData, clearData, type AppData } from '../services/storage'
import { exportAllData, clearAllData, getStorageUsage } from '../services/indexedDBStorage'
import { formatFileSize } from '../utils/imageUtils'
import { authState } from '../services/auth'
import ImageManager from './ImageManager.vue'
import ChangePasswordModal from './ChangePasswordModal.vue'

/**
 * 设置组件
 * 提供数据导入导出、清除等功能
 */
const props = defineProps<{
  appData: AppData
}>()

const emit = defineEmits<{
  dataImported: [data: AppData]
  close: []
}>()

// 存储使用情况
const storageUsage = ref({ used: 0, available: 0 })
const isExporting = ref(false)

// 文件输入引用
const fileInput = ref<HTMLInputElement | null>(null)

// 功能模块状态
const showImageManager = ref(false)
const showChangePasswordModal = ref(false)

/**
 * 导出数据（包含图片）
 */
const handleExportData = async () => {
  isExporting.value = true
  try {
    const allData = await exportAllData()

    const jsonData = JSON.stringify(allData, null, 2)
    const blob = new Blob([jsonData], { type: 'application/json' })
    const url = URL.createObjectURL(blob)

    const link = document.createElement('a')
    link.href = url
    link.download = `linkbook-full-backup-${new Date().toISOString().split('T')[0]}.json`
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)

    URL.revokeObjectURL(url)
    console.log('完整数据导出成功')
  } catch (error) {
    console.error('导出数据失败:', error)
    // 降级到基础导出
    exportData(props.appData)
  } finally {
    isExporting.value = false
  }
}

/**
 * 触发文件选择
 */
const triggerFileSelect = () => {
  fileInput.value?.click()
}

/**
 * 处理文件导入
 * @param event 文件选择事件
 */
const handleFileImport = async (event: Event) => {
  const target = event.target as HTMLInputElement
  const file = target.files?.[0]

  if (file) {
    try {
      const data = await importData(file)
      if (data) {
        emit('dataImported', data)
        alert('数据导入成功！')
      }
    } catch (error) {
      alert('导入失败：数据格式不正确')
    }

    // 清空文件输入
    target.value = ''
  }
}

/**
 * 清除所有数据
 */
const handleClearData = async () => {
  if (confirm('确定要清除所有数据吗？此操作不可恢复！')) {
    try {
      await clearAllData()
      clearData() // 同时清除localStorage
      location.reload() // 重新加载页面
    } catch (error) {
      console.error('清除数据失败:', error)
      clearData()
      location.reload()
    }
  }
}

/**
 * 获取存储使用情况
 */
const updateStorageUsage = async () => {
  try {
    storageUsage.value = await getStorageUsage()
  } catch (error) {
    console.error('获取存储使用情况失败:', error)
  }
}

/**
 * 打开图片管理器
 */
const openImageManager = (): void => {
  showImageManager.value = true
}

/**
 * 关闭图片管理器
 */
const closeImageManager = (): void => {
  showImageManager.value = false
}

/**
 * 打开修改密码弹窗
 */
const openChangePassword = (): void => {
  showChangePasswordModal.value = true
}

/**
 * 关闭修改密码弹窗
 */
const closeChangePassword = (): void => {
  showChangePasswordModal.value = false
}

/**
 * 修改密码成功回调
 */
const handlePasswordChangeSuccess = (): void => {
  console.log('密码修改成功')
  closeChangePassword()
}

// 组件挂载时获取存储使用情况
onMounted(() => {
  updateStorageUsage()
})

/**
 * 关闭设置面板
 */
const closeSettings = () => {
  emit('close')
}
</script>

<template>
  <div class="settings-overlay" @click="closeSettings">
    <div class="settings-panel" @click.stop>
      <div class="settings-header">
        <h2>设置</h2>
        <button class="close-btn" @click="closeSettings">
          <svg viewBox="0 0 24 24" width="20" height="20">
            <path
              fill="currentColor"
              d="M19 6.41L17.59 5 12 10.59 6.41 5 5 6.41 10.59 12 5 17.59 6.41 19 12 13.41 17.59 19 19 17.59 13.41 12z"
            />
          </svg>
        </button>
      </div>

      <div class="settings-content">
        <!-- 功能管理 -->
        <div class="settings-section">
          <h3>功能管理</h3>
          <div class="settings-group">
            <div class="setting-item">
              <div class="setting-info">
                <h4>图片管理</h4>
                <p>管理应用中的所有图片资源</p>
              </div>
              <button class="setting-btn" @click="openImageManager">
                <svg viewBox="0 0 24 24" width="16" height="16" style="margin-right: 6px;">
                  <path fill="currentColor" d="M21 19V5c0-1.1-.9-2-2-2H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2zM8.5 13.5l2.5 3.01L14.5 12l4.5 6H5l3.5-4.5z"/>
                </svg>
                打开图片管理
              </button>
            </div>
            
            <div v-if="authState.isLoggedIn" class="setting-item">
              <div class="setting-info">
                <h4>修改密码</h4>
                <p>更改您的账户密码</p>
              </div>
              <button class="setting-btn" @click="openChangePassword">
                <svg viewBox="0 0 24 24" width="16" height="16" style="margin-right: 6px;">
                  <path fill="currentColor" d="M12,17A2,2 0 0,0 14,15C14,13.89 13.1,13 12,13A2,2 0 0,0 10,15A2,2 0 0,0 12,17M18,8A2,2 0 0,1 20,10V20A2,2 0 0,1 18,22H6A2,2 0 0,1 4,20V10C4,8.89 4.9,8 6,8H7V6A5,5 0 0,1 12,1A5,5 0 0,1 17,6V8H18M12,3A3,3 0 0,0 9,6V8H15V6A3,3 0 0,0 12,3Z"/>
                </svg>
                修改密码
              </button>
            </div>
          </div>
        </div>
        
        <!-- 数据管理 -->
        <div class="settings-section">
          <h3>数据管理</h3>
          <div class="settings-group">
            <div class="setting-item">
              <div class="setting-info">
                <h4>导出数据</h4>
                <p>将所有笔记、文件夹和图片导出为JSON文件</p>
              </div>
              <button class="setting-btn primary" @click="handleExportData" :disabled="isExporting">
                {{ isExporting ? '导出中...' : '导出' }}
              </button>
            </div>

            <div class="setting-item">
              <div class="setting-info">
                <h4>导入数据</h4>
                <p>从JSON文件导入笔记和文件夹数据</p>
              </div>
              <button class="setting-btn" @click="triggerFileSelect">导入</button>
              <input
                ref="fileInput"
                type="file"
                accept=".json"
                @change="handleFileImport"
                style="display: none"
              />
            </div>

            <div class="setting-item">
              <div class="setting-info">
                <h4>清除数据</h4>
                <p class="warning">删除所有本地数据，此操作不可恢复</p>
              </div>
              <button class="setting-btn danger" @click="handleClearData">清除</button>
            </div>
          </div>
        </div>

        <div class="settings-section">
          <h3>存储信息</h3>
          <div class="settings-group">
            <div class="info-item">
              <span class="info-label">已使用空间</span>
              <span class="info-value">{{ formatFileSize(storageUsage.used) }}</span>
            </div>
            <div class="info-item" v-if="storageUsage.available > 0">
              <span class="info-label">可用空间</span>
              <span class="info-value">{{ formatFileSize(storageUsage.available) }}</span>
            </div>
            <div class="info-item">
              <span class="info-label">存储使用率</span>
              <span class="info-value">
                {{
                  storageUsage.available > 0
                    ? Math.round((storageUsage.used / storageUsage.available) * 100) + '%'
                    : 'N/A'
                }}
              </span>
            </div>
          </div>
        </div>

        <div class="settings-section">
          <h3>应用信息</h3>
          <div class="settings-group">
            <div class="info-item">
              <span class="info-label">版本</span>
              <span class="info-value">1.0.0</span>
            </div>
            <div class="info-item">
              <span class="info-label">笔记数量</span>
              <span class="info-value">{{ appData.notes.length }}</span>
            </div>
            <div class="info-item">
              <span class="info-label">文件夹数量</span>
              <span class="info-value">{{ appData.folders.length }}</span>
            </div>
            <div class="info-item">
              <span class="info-label">存储方式</span>
              <span class="info-value">IndexedDB + LocalStorage</span>
            </div>
          </div>
        </div>
      </div>
    </div>
    
    <!-- 图片管理器 -->
    <ImageManager v-if="showImageManager" @close="closeImageManager" />
    
    <!-- 修改密码弹窗 -->
    <ChangePasswordModal 
      v-if="showChangePasswordModal" 
      @success="handlePasswordChangeSuccess"
      @close="closeChangePassword" 
    />
  </div>
</template>

<style scoped>
.settings-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.settings-panel {
  background: white;
  border-radius: 12px;
  width: 90%;
  max-width: 600px;
  max-height: 80vh;
  overflow-y: auto;
  box-shadow: 0 20px 40px rgba(0, 0, 0, 0.1);
}

.settings-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 20px 24px;
  border-bottom: 1px solid #e9ecef;
}

.settings-header h2 {
  margin: 0;
  font-size: 20px;
  font-weight: 600;
  color: #212529;
}

.close-btn {
  padding: 8px;
  border: none;
  border-radius: 6px;
  background: transparent;
  cursor: pointer;
  color: #6c757d;
  transition: all 0.2s;
}

.close-btn:hover {
  background: #f8f9fa;
  color: #212529;
}

.settings-content {
  padding: 24px;
}

.settings-section {
  margin-bottom: 32px;
}

.settings-section:last-child {
  margin-bottom: 0;
}

.settings-section h3 {
  margin: 0 0 16px 0;
  font-size: 16px;
  font-weight: 600;
  color: #212529;
}

.settings-group {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.setting-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 16px;
  border: 1px solid #e9ecef;
  border-radius: 8px;
  background: #f8f9fa;
}

.setting-info {
  flex: 1;
}

.setting-info h4 {
  margin: 0 0 4px 0;
  font-size: 14px;
  font-weight: 600;
  color: #212529;
}

.setting-info p {
  margin: 0;
  font-size: 13px;
  color: #6c757d;
  line-height: 1.4;
}

.setting-info p.warning {
  color: #dc3545;
}

.setting-btn {
  padding: 8px 16px;
  border: 1px solid #dee2e6;
  border-radius: 6px;
  background: white;
  cursor: pointer;
  font-size: 14px;
  font-weight: 500;
  transition: all 0.2s;
  margin-left: 16px;
}

.setting-btn:hover {
  background: #f8f9fa;
}

.setting-btn.primary {
  background: #007bff;
  border-color: #007bff;
  color: white;
}

.setting-btn.primary:hover {
  background: #0056b3;
  border-color: #0056b3;
}

.setting-btn.danger {
  background: #dc3545;
  border-color: #dc3545;
  color: white;
}

.setting-btn.danger:hover {
  background: #c82333;
  border-color: #c82333;
}

.info-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 16px;
  border: 1px solid #e9ecef;
  border-radius: 6px;
  background: white;
}

.info-label {
  font-size: 14px;
  color: #6c757d;
}

.info-value {
  font-size: 14px;
  font-weight: 600;
  color: #212529;
}
</style>
